﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using hotel.DAL;
using hotel.Common;
using hotel.Win.BaseData;
using hotel.Win.Common;
using hotel.MyUserControl;

namespace hotel.Win.Subscribe
{
    /// <summary>
    /// 接待登记
    /// </summary>
    public partial class jddjFrm : Form
    {
        #region 专有变量

        private int JDBZ;//接待标志0=预订，1=入住
        private string FH;//房号        
        private bool IsEdit;
        private List<YXRoom> kxRoom = new List<YXRoom>();//可选择的房间
        private List<YXRoom> yxRoom = new List<YXRoom>();//已经选择的房间
        private hotelEntities _context;
        private RZJL rzjlModel;//入住记录模型
        private RZRY currentRzryModel;//当前入住人员模型
        private List<RZRY> Rzrys = new List<RZRY>();//入住人员模型集合
        private bool IsNewRZRY;//是否是新增入住人员
        private ROOM roomModel;//主房间
        #endregion
        #region 公有属性
        /// <summary>
        /// 是否是多开房
        /// </summary>
        public bool IsMutilRoom { get; private set; }
        /// <summary>
        /// 所有登记房间
        /// </summary>
        public List<string> RoomIds { get; private set; }
         
        #endregion
        public jddjFrm()
        {
            InitializeComponent();
            _context = MyDataContext.GetDataContext;
            dtpddrq.Enabled = false;
            btnprintJy.Visible = false;
            this.dtpldrq.ValueChanged -= new System.EventHandler(this.dtpldrq_ValueChanged);
            this.dtpddrq.ValueChanged -= new System.EventHandler(this.dtpldrq_ValueChanged);
            cobxzzfs.DisplayMember = "XMMC";
            cobxzzfs.ValueMember = "XMDM";
            cobxzzfs.DataSource = XTCYDMDal.GetAllByLBDM(EnumXtcydmLB.ZFFS.ToString());
            
            //目前在住的团体
            var qry= (from q in _context.RZJL.AsNoTracking()
                                   where q.TDMC != null
                                   orderby q.TDMC
                                   select new NameValue
                                   { 
                                       Name =q.TDMC,
                                       Value = q.TDDM == null?q.TDMC:q.TDDM
                                   }).Distinct();
            cobxtdmc.DataSource = qry.ToList();
            cobxtdmc.SelectedIndex = -1;
            cobxtdmc.Text = "";
            cobxkrlb.Items.Clear();
            cobxkrlb.Items.AddRange(RoomStstusCnName.GetJeiDaiAvailables.ToArray());
           
            tabMain.SelectedIndex = 0;            
            plrd.Visible = false;
            plrz.Visible = false;
            
        }
        /// <summary>
        /// [修改]接待登记，包括预订和正式入住
        /// </summary>
        /// <param name="rzzh">入住帐号</param>
        /// <param name="jdbz">接待标志 0=预订，1=入住,2=继续新预订</param>
        /// <param name="context">The context.</param>
        /// <param name="isShowRy">直接显示人员信息Tab</param>
        public jddjFrm(string rzjlId, int jdbz,bool isShowRy =false):this()
        {
            rzjlModel = _context.RZJL.Find(rzjlId);
            this.JDBZ = jdbz;
            IsNewRZRY = false;
            roomModel = _context.ROOM.Find(rzjlModel.ROOM_ID);
            SetRoomDispaly();
            if (jdbz == 0)
            {
                plrd.Visible = true;
                this.Text = "修改预订登记";
                this.btnsave.Text = "保存预定";
                dtpddrq.Enabled = true;
                //cobxkrlb.Items.Insert(0, RoomStstusCnName.YuDing);
            }
            else if (jdbz == 1)
            {
                plrz.Visible = true;
                this.Text = "修改入住登记";
                this.btnsave.Text = "保存入住";               
            }
            else
                throw new Exception("没有定义的接待标志");
            cobxkrlb.MaxDropDownItems = cobxkrlb.Items.Count;
            
          
            //修改
            txtbzsm.Text = rzjlModel.BZSM;
            lbzh.Text = rzjlModel.ID;
            if (!string.IsNullOrEmpty(rzjlModel.TDDM))
            {
                cobxtdmc.DataSource = new List<NameValue> { (new hotel.Common.NameValue() { Name = rzjlModel.TDMC, Value = rzjlModel.TDDM }) };
                cobxtdmc.SelectedIndex = 0;
            }
            if (!string.IsNullOrEmpty(rzjlModel.XYDW_DM))
            {
                cobxxydw.Items.Add(new hotel.Common.NameValue() { Name = rzjlModel.XYDW_MC, Value = rzjlModel.XYDW_DM });
                cobxxydw.SelectedIndex = 0;
            }
            //协议房价
            cobxsyjg.DisplayMember = "XYMC";
            var syDatas = _context.RoomTypePrice.AsNoTracking().Where(p => p.ROOM_TYPE_ID == roomModel.ROOM_TYPE_ID && p.SFXS == "是").ToList();
            cobxsyjg.DataSource = syDatas;
            cobxsyjg.SelectedItem = syDatas.FirstOrDefault(p => p.XYMC == rzjlModel.XYJG_MC);
            dtpddrq.Value = Convert.ToDateTime(rzjlModel.DDRQ);
            dtpldrq.Value = Convert.ToDateTime(rzjlModel.LDRQ);
            cobxkrlb.Text = rzjlModel.KRLB;
            txtrs.Value = (decimal)rzjlModel.RS;
            txtfz.Value = (decimal)rzjlModel.SJFJ;
            txtts.Value = (decimal)rzjlModel.TS;
            txtyj.Value = (decimal)rzjlModel.YJ;
            cobxzzfs.Text = rzjlModel.ZFFS;
            txtzk.Value = (decimal)rzjlModel.ZK;
            

            IsEdit = true;
            txtyj.Enabled = false;
            //不能修改房间
            btnzj.Enabled = false;
            btnyc.Enabled = false;
            BindRZRYXX();
            this.dtpldrq.ValueChanged += new System.EventHandler(this.dtpldrq_ValueChanged);
            this.dtpddrq.ValueChanged += new System.EventHandler(this.dtpldrq_ValueChanged);
            if (isShowRy)
                tabMain.SelectedIndex = 1;
        }

        //房间显示信息
        private void SetRoomDispaly()
        {
            if (roomModel == null)
                throw new Exception("房间数据为空，请查证！roomModel ");
            //房间数据
            lbfh.Text = roomModel.ID;
            lbysj.Text = roomModel.SKFJ.ToString();
            lbfl.Text = roomModel.ROOM_TYPE.JC;
            this.FH = roomModel.ID;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="room"></param>
        /// <param name="jdbz"></param>
        /// <param name="context"></param>
        public jddjFrm(string roomId, int jdbz)
            : this()
        {
            btnprintJy.Visible = true;
            btnprintJy.Enabled = false;
            this.JDBZ = jdbz;
            IsNewRZRY = true;
            roomModel = _context.ROOM.Find(roomId);
            SetRoomDispaly();
            cobxsyjg.DisplayMember = "XYMC";
            var syDatas = _context.RoomTypePrice.Where(p => p.ROOM_TYPE_ID == roomModel.ROOM_TYPE_ID && p.SFXS=="是").ToList();
            cobxsyjg.DataSource = syDatas;
           
            if (jdbz == 0)
            {
                plrd.Visible = true;
                this.Text = "新预订登记";
                this.btnsave.Text = "保存预定";
                cobxkrlb.SelectedIndex = 0;
                dtpddrq.Enabled = true;
                txtyj.Value = 0;  
            }
            else if (jdbz == 1)
            {                
                plrz.Visible = true;
                this.Text = "新入住登记";
                this.btnsave.Text = "保存入住";
                cobxkrlb.SelectedIndex = 0;
                //txtyj.Value = roomModel.ROOM_TYPE.YJ;
                txtyj.Value = 0;  
            }
            else
                throw new Exception("没有定义的接待标志");
            cobxkrlb.MaxDropDownItems = cobxkrlb.Items.Count;
            //选择默认
            cobxsyjg.SelectedItem = syDatas.FirstOrDefault(p => p.SFMR == "是");
           
            if (cobxsyjg.SelectedIndex < 0)
            {
                txtfz.Text = lbysj.Text;
                txtzk.Text = "1.00";
            }
              
                
            IsEdit = false;
            //新帐号                       
            lbzh.Text = _context.GetRZXH().Single();
            rzjlModel = new RZJL { ID = lbzh.Text };
                  
            txtyj.Enabled = true;
            txtrs.Value = 1;
            dtpddrq.Value = DateTime.Now;
          
            var xtcs = XTCSModel.GetXTCS;
            dtpldrq.Value =  Convert.ToDateTime(DateTime.Now.AddDays(1).Date.ToString("yyyy-MM-dd ") + xtcs.JBTFZ_SJ);
            
            txtts.Value = 1;
            cobxzzfs.SelectedIndex = 0;

            yxRoom.Add(new YXRoom() { ID = roomModel.ID, FJZL = lbfl.Text, FJ = roomModel.SKFJ });
            InidGridData();
            BindGrid();
            btnkrzj_Click(btnkrzj, null);
            tabMain.TabPages[1].Text = "新增加住客";
            plrz.Visible = false;
            plrd.Visible = false;
            this.dtpldrq.ValueChanged += new System.EventHandler(this.dtpldrq_ValueChanged);
            this.dtpddrq.ValueChanged += new System.EventHandler(this.dtpldrq_ValueChanged);
        }
       
        private void BindRZRYXX()
        {
            Rzrys = _context.RZRY.Where(p => p.RZJL.ID == rzjlModel.ID && p.KRZT == "在住").ToList();
            if (Rzrys.Count == 0)
            {
                MessageBox.Show("没有找到入住人员");
                return;
            }
            foreach (var item in Rzrys)
            {
                var page1 = new TabPage(item.KRXM);
                tabkrxx.Controls.Add(page1);
                var uckrxx1 = new uckrxx(item);
                uckrxx1.FindCallBack = uckrxxFindCallBack;
                page1.Controls.Add(uckrxx1);
            }
            IsNewRZRY = false;
            tabkrxx.SelectedIndex = 0;
            currentRzryModel = Rzrys.First();
            btnkrsc.Enabled = Rzrys.Count > 1;
            txtkrld.Enabled = Rzrys.Count > 1;
            btndy.Enabled = Rzrys.Count > 0;
        }

        /// <summary>
        /// 初始化表格数据
        /// </summary>
        private void InidGridData()
        {
            var qry = from r in _context.ROOM.AsNoTracking()
                      join t in _context.ROOM_TYPE.AsNoTracking() on r.ROOM_TYPE.ID equals t.ID
                      where r.ZT == RoomStstusCnName.YuDing || r.ZT == RoomStstusCnName.KongJing
                      orderby r.ID
                      select new YXRoom
                      {
                          ID = r.ID,
                          FJ = r.SKFJ,
                          FJZL = t.JC,
                          YDF = r.ZT == RoomStstusCnName.YuDing ? "是" : "否"
                      };

            if (qry.Count() == 1)
                return; //=1表示当前房号
            //左外联接，不包含p2
            //var qry1 = from p1 in qry.ToList()
            //           join p2 in yxRoom on p1.ID equals p2.ID into gj
            //           from sub in gj.DefaultIfEmpty()
            //           where sub == null
            //           select new YXRoom
            //           {
            //               ID = p1.ID,
            //               FJZL = p1.JC,
            //               FJ = p1.SKFJ,
            //               YDF = p1.ZT == "预订房" ? "是" : "否"
            //           };
            kxRoom = qry.ToList();
            var currroom = kxRoom.FirstOrDefault(p => p.ID == FH);
            if (currroom != null)
                kxRoom.Remove(currroom);
            btnyc.Enabled = yxRoom.Count > 1;
        }
        private void BindGrid()
        {
            grid1.AutoGenerateColumns = false;
            grid1.DataSource = null;
            grid1.DataSource = kxRoom;
            grid2.AutoGenerateColumns = false;
            grid2.DataSource = null;
            grid2.DataSource = yxRoom;
            btnyc.Enabled = yxRoom.Count > 1;
            btnzj.Enabled = kxRoom.Count > 0;
        }

        /// <summary>
        /// 已选room临时类
        /// 因为此类要做临时修改，能有原有room
        /// </summary>
        private class YXRoom
        {
            public string ID { get; set; }
            public string FJZL { get; set; }
            public decimal? FJ { get; set; }
            public string YDF { get; set; }
        }

        private void btnclose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnzj_Click(object sender, EventArgs e)
        {
            string id = Common.ControlsUtility.GetActiveGridValue(grid1, "GRID1_ID");
            if (id == "")
                return;
            var r1 = kxRoom.First(p => p.ID == id);
            if (yxRoom.Count(p => p.ID == id) == 0)
                yxRoom.Add(new YXRoom() { ID = id, FJZL = r1.FJZL, FJ = r1.FJ, YDF = r1.YDF });
            kxRoom.Remove(r1);
            BindGrid();
        }

        private void btnyc_Click(object sender, EventArgs e)
        {
            string id = Common.ControlsUtility.GetActiveGridValue(grid2, "GRID2_ID");
            if (id == FH)
            {
                MessageBox.Show("主房号不能删除");
                return;
            }
            if (id == "")
                return;
            var r2 = yxRoom.First(p => p.ID == id);
            if (kxRoom.Count(p => p.ID == id) == 0)
                kxRoom.Add(new YXRoom() { ID = id, FJZL = r2.FJZL, FJ = r2.FJ, YDF = r2.YDF });
            yxRoom.Remove(r2);
            BindGrid();
        }

        private void txtfz_Leave(object sender, EventArgs e)
        {
            txtzk.Value = Math.Round(txtfz.Value / Convert.ToDecimal(lbysj.Text),2);
        }

        private void txtzk_Leave(object sender, EventArgs e)
        {
            txtfz.Value = Convert.ToDecimal(lbysj.Text) * txtzk.Value;
        }

        private void tabMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabMain.SelectedIndex == 1 && !IsEdit)
            {
                MessageBox.Show("请先保存房间信息，在维护客人信息");
                tabMain.SelectedIndex = 0;
                return;
            }
        }

        /// <summary>
        /// 房间信息保存[主页面]
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnsave_Click(object sender, EventArgs e)
        {
            if (!CheckData())
                return;
            btnsave.Enabled = false;
            string logroomIds="";
            //写操作日志
            CcrzInfo logInfo = new CcrzInfo();
            logInfo.RoomId = roomModel.ID;
            logInfo.Type = LogTypeEnum.涉及金额;
            if (IsEdit)
            {
                if (  rzjlModel.SJFJ != txtfz.Value)
                    logInfo.Message = "修改房租，原=" + rzjlModel.SJFJ.Value.ToString() + ",新=" + txtfz.Value.ToString();
            }
            else
            {
                logInfo.Message = "房租=" + txtfz.Value.ToString()+ "，押金=" + txtyj.Value.ToString();
            }
           
            rzjlModel.BZSM = txtbzsm.Text;
            if (cobxtdmc.SelectedItem!=null)
            {
                rzjlModel.TDDM = (cobxtdmc.SelectedItem as NameValue).Value;
                rzjlModel.TDMC = (cobxtdmc.SelectedItem as NameValue).Name;
            }
            else if(cobxtdmc.Text.Length >0)
            {
                rzjlModel.TDDM = cobxtdmc.Text;
                rzjlModel.TDMC = cobxtdmc.Text;
            }

            if (cobxxydw.SelectedIndex == 0)
            {
                rzjlModel.XYDW_DM = (cobxxydw.SelectedItem as NameValue).Value;
                rzjlModel.XYDW_MC = (cobxxydw.SelectedItem as NameValue).Name;
            }
          
            rzjlModel.LDRQ = dtpldrq.Value;
            rzjlModel.KRLB = cobxkrlb.Text;
            rzjlModel.ROOM = roomModel;
            rzjlModel.RS = (int)txtrs.Value;
            rzjlModel.SJFJ = txtfz.Value;
            rzjlModel.SKFJ = roomModel.SKFJ;
            rzjlModel.TS = (int)txtts.Value;            
            rzjlModel.ZFFS = cobxzzfs.Text;
            rzjlModel.ZK = txtzk.Value;
            rzjlModel.XYJG_MC = cobxsyjg.Text;
            if (IsEdit)
            {
                rzjlModel.XGRQ = DateTime.Now;
                rzjlModel.XGRY = UserLoginInfo.FullName;
                if (JDBZ == 1)
                {
                    roomModel.ZT = cobxkrlb.Text;
                    logInfo.Abstract = LogAbstractEnum.修改登记;
                }
                else
                {
                    logInfo.Abstract = LogAbstractEnum.修改预订;
                }
            }
            else
            {
                rzjlModel.DDRQ = dtpddrq.Value;
                rzjlModel.YJ = (int)txtyj.Value;
                rzjlModel.CJRQ = DateTime.Now;
                rzjlModel.CJRY = UserLoginInfo.FullName;
                if (JDBZ == 1)
                {
                    roomModel.ZT = cobxkrlb.Text;
                    roomModel.RZBZ = "是";
                    rzjlModel.YDBZ = "否";
                    rzjlModel.RZBZ = "是";
                    logInfo.Abstract = LogAbstractEnum.客人登记;
                }
                else
                {
                    rzjlModel.RZBZ = "否";
                    rzjlModel.YDBZ = "是";                    
                    logInfo.Abstract = LogAbstractEnum.客人预订;
                }
               
                IsEdit = true;
                txtyj.Enabled = false;
                _context.RZJL.Add(rzjlModel);
                //如果押金不为0增加消费记录
                if (txtyj.Value > 0)
                {
                    btnprintJy.Enabled = true;
                    var xfjlModel = new XFJL();
                    xfjlModel.CJRQ = DateTime.Now;
                    xfjlModel.CJRY = UserLoginInfo.FullName;
                    xfjlModel.DJ = 0;
                    xfjlModel.JE = 0;
                    xfjlModel.SL = 1;
                    xfjlModel.ROOM = roomModel;
                    xfjlModel.RZJL = rzjlModel;
                    xfjlModel.XFXM = _context.XFXM.First(p => p.DM == "YJ");//系统固定= 押金
                    xfjlModel.XFXM_MC = xfjlModel.XFXM.MC;
                    xfjlModel.XFBZ = "押";
                    xfjlModel.YJ = (int)txtyj.Value;
                    xfjlModel.ZFFS = cobxzzfs.Text;
                    _context.XFJL.Add(xfjlModel);
                }
                //钟点房，自动增加一次房费
                if (RoomStstusCnName.ZhongDian == rzjlModel.XYJG_MC)
                {
                    var xfjlModel = new XFJL();
                    xfjlModel.CJRQ = DateTime.Now;
                    xfjlModel.CJRY = UserLoginInfo.FullName;
                    xfjlModel.DJ = txtfz.Value;
                    xfjlModel.JE = txtfz.Value;
                    xfjlModel.SL = 1;
                    xfjlModel.ROOM = roomModel;
                    xfjlModel.RZJL = rzjlModel;
                    xfjlModel.XFXM = _context.XFXM.First(p => p.DM == "FZ");//系统固定= 房租
                    xfjlModel.XFXM_MC = xfjlModel.XFXM.MC;
                    xfjlModel.XFBZ = "消";
                    xfjlModel.YJ = 0;
                    xfjlModel.BZSM = "钟点房初始";
                    xfjlModel.ZFFS = cobxzzfs.Text;
                    _context.XFJL.Add(xfjlModel);
                }
                //一次入住多个房间
                if (grid2.Rows.Count > 1)
                {                    
                    rzjlModel.LFH = _context.GetLfh();
                    IsMutilRoom = true;
                    RoomIds = new List<string>();
                    List<string> rooms = new List<string>();
                    foreach (DataGridViewRow item in grid2.Rows)
                    {
                        rooms.Add(item.Cells["GRID2_ID"].Value.ToString());
                        if (logroomIds.Length >0)
                            logroomIds +=",";
                        logroomIds += item.Cells["GRID2_ID"].Value.ToString();
                    }
                    RoomIds = rooms;
                    CreateFJYDF(rooms);
                    logInfo.Message += "关联房间:" + logroomIds;
                }
            }
            _context.SaveChanges();
            
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message += ",客类：" + rzjlModel.KRLB;
            CCRZManager.Add(logInfo);
            MessageBox.Show(this.Text + "房间休息保存成功,你可以增加客人信息");
            //不能在增加关联
            btnzj.Enabled = false;
            btnyc.Enabled = false;
            
            btnsave.Enabled = true;
            //if (!IsEdit && txtyj.Value > 0&& XTCSModel.GetXTCS.SFDY_YYD &&
            //    MessageBox.Show("是否打印押金条?", hotel.Common.SysConsts.SysInformationCaption, MessageBoxButtons.OKCancel)== DialogResult.OK)
            //{
            //    MessageBox.Show("test");
            //}
        }

        private bool CheckData()
        {
            if (dtpldrq.Value < dtpddrq.Value)
            {
                MessageBox.Show("离店日期不小于抵店日期");
                return false;
            }
            if (txtfz.Value < 0)
            {
                MessageBox.Show("房租不能小于0，请查证");
                return false;
            }
            if (!IsEdit && JDBZ == 0)
            {
                //预订时间是否有交叉,没有检查同开放
                if (_context.RZJL.Count(p => p.ROOM.ID == lbfh.Text && p.YDBZ == "是" && dtpddrq.Value >= p.DDRQ && dtpddrq.Value <= p.LDRQ) > 0)
                {
                    MessageBox.Show("此抵店时间，已经有人预订，请查证！");
                    return false;
                }
                if (_context.RZJL.Count(p => p.ROOM.ID == lbfh.Text && p.YDBZ == "是" && dtpldrq.Value >= p.DDRQ && dtpldrq.Value <= p.LDRQ) > 0)
                {
                    MessageBox.Show("此离店时间，已经有人预订，请查证！");
                    return false;
                }
                if (_context.RZJL.Count(p => p.ROOM.ID == lbfh.Text && p.YDBZ == "是" && p.DDRQ >= dtpddrq.Value && p.DDRQ <= dtpldrq.Value) > 0)
                {
                    MessageBox.Show("此抵店时间，已经有人预订，请查证！");
                    return false;
                }
                if (_context.RZJL.Count(p => p.ROOM.ID == lbfh.Text && p.YDBZ == "是" && p.LDRQ >= dtpddrq.Value && p.LDRQ <= dtpldrq.Value) > 0)
                {
                    MessageBox.Show("此离店时间，已经有人预订，请查证！");
                    return false;
                }
            }
            //入住押金不能为0
            if (!IsEdit && JDBZ == 1)
            {
                if (txtyj.Value <= 0)
                {
                    MessageBox.Show("入住时押金不能小于0，请查证");
                    txtyj.Focus();
                    return false;
                }               
            }
            return true;
        }

        #region 直接入住按钮
        private void btnyjcl_Click(object sender, EventArgs e)
        {
            var frm = new yjclFrm(lbzh.Text);
            frm.ShowDialog();
            this.Close();
        }
        /// <summary>
        /// 消费入单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnxf_Click(object sender, EventArgs e)
        {
            var frm = new krfyMaintain(lbzh.Text);
            frm.ShowDialog();
            this.Close();
        }

        /// <summary>
        /// 结帐退房
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnjz_Click(object sender, EventArgs e)
        {
            var frm = new jztfFrm(lbzh.Text);
            frm.ShowDialog();
            this.Close();

        }


        #endregion

        #region 预订按钮

        /// <summary>
        /// 加预订房
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnjydf_Click(object sender, EventArgs e)
        {
            var frm = new fjFindForYd();
            if (frm.ShowDialog() != DialogResult.OK)
                return;
            CreateFJYDF(frm.Rooms);

            #region 日志纪录
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.客人预订加房;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "新增加的房间:" + frm.Rooms.ToString(",");
            logInfo.Save();
            #endregion
           
            MessageBox.Show("新加预订房成功");
            this.Close();           
        }

        /// <summary>
        /// 处理附加的预订房
        /// </summary>
        /// <param name="rooms"></param>
        private void CreateFJYDF(List<string> rooms)
        {
            if (RoomIds == null)
                RoomIds = new List<string>();
            foreach (var roomid in rooms)
            {
                if (roomid == roomModel.ID)
                    continue;
                if (!CheckData())
                    return;
                if (!RoomIds.Contains(roomid))
                    RoomIds.Add(roomid);

                var xrzjlModel = new RZJL { ID = _context.GetRZXH().Single() };
                xrzjlModel.F_ID = rzjlModel.ID; //父子关系
                if (string.IsNullOrEmpty(rzjlModel.LFH))
                    rzjlModel.LFH = _context.GetLfh();
                xrzjlModel.LFH = rzjlModel.LFH;
                xrzjlModel.XYJG_MC = rzjlModel.XYJG_MC;
                xrzjlModel.BZSM =rzjlModel.ROOM_ID + "的子房间";

                if (cobxtdmc.SelectedIndex == 0)
                {
                    xrzjlModel.TDDM = (cobxtdmc.SelectedItem as NameValue).Value;
                    xrzjlModel.TDMC = (cobxtdmc.SelectedItem as NameValue).Name;
                }
                if (cobxxydw.SelectedIndex == 0)
                {
                    xrzjlModel.XYDW_DM = (cobxxydw.SelectedItem as NameValue).Value;
                    xrzjlModel.XYDW_MC = (cobxxydw.SelectedItem as NameValue).Name;
                }
                xrzjlModel.DDRQ = dtpddrq.Value;
                xrzjlModel.LDRQ = dtpldrq.Value;
                xrzjlModel.KRLB = cobxkrlb.Text;
               
                xrzjlModel.RS = (int)txtrs.Value;
                xrzjlModel.SJFJ = txtfz.Value;
                xrzjlModel.SKFJ = roomModel.SKFJ;
                xrzjlModel.TS = (int)txtts.Value;
                xrzjlModel.YJ = 0;
                xrzjlModel.ZFFS = cobxzzfs.Text;
                xrzjlModel.ZK = txtzk.Value;

                xrzjlModel.CJRQ = DateTime.Now;
                xrzjlModel.CJRY = UserLoginInfo.FullName;
                var xroomModel = _context.ROOM.First(p=>p.ID == roomid);
                xrzjlModel.ROOM = xroomModel;

                if (JDBZ == 1)
                {
                    xroomModel.ZT = cobxkrlb.Text;
                    xroomModel.RZBZ = "是";
                    xrzjlModel.YDBZ = "否";
                    xrzjlModel.RZBZ = "是";
                }
                else
                {
                    xrzjlModel.YDBZ = "是";
                    xrzjlModel.RZBZ = "否";
                }
                

                IsEdit = true;
                _context.RZJL.Add(xrzjlModel);
                //入住人员
                var rzryModel = new RZRY();
                rzryModel.KRZT = "在住";
                rzryModel.CJRQ = DateTime.Now;
                rzryModel.CJRY = UserLoginInfo.FullName;
                rzryModel.KRXM = "新客人";
                rzryModel.BZSM = "联房" + rzjlModel.ROOM_ID;
                rzryModel.RZJL = xrzjlModel;
                _context.RZRY.Add(rzryModel);
            }
            _context.SaveChanges();
        }

        private void btncxrd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(rzjlModel.F_ID))
            {
                MessageBox.Show("子预定不能取消，请选择主预定房间");
                return;
            }
            //子房间有入住
            if (_context.RZJL.Count(p => p.F_ID == rzjlModel.ID && p.RZBZ == "是") > 0)
            {
                MessageBox.Show("此预定有子房间已经入住，不能取消!");
                return;
            }
            var sumYj = _context.XFJL.Where(p => p.RZJL_ID == rzjlModel.ID).Sum(p => p.YJ);
            if (MessageBox.Show("客人押金：" + sumYj.ToString()+"\n你确定取消预订吗？", hotel.Common.SysConsts.SysWarningCaption, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                return;
            #region 日志纪录
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.预订取消;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "预定押金=" + sumYj.ToString();
            logInfo.Save();
            #endregion
            using (var tempContext = MyDataContext.GetDataContext)
            {
                tempContext.RZJL_QXYD_PROC(string.IsNullOrEmpty(rzjlModel.F_ID) ? rzjlModel.ID : rzjlModel.F_ID, UserLoginInfo.FullName);
            }
            MessageBox.Show("预订已经取消，窗口将关闭");           
            this.Close();
        }

        /// <summary>
        /// 预订入住
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnydrz_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定将预订转为入住吗？别忘记收押金啊！", hotel.Common.SysConsts.SysWarningCaption, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                return;
            rzjlModel.DDRQ = DateTime.Now;
            rzjlModel.YDBZ = "否";
            rzjlModel.RZBZ = "是";
            rzjlModel.ROOM.RZBZ = "是";
            rzjlModel.ROOM.ZT = cobxkrlb.Text == RoomStstusCnName.YuDing ? RoomStstusCnName.SanKe : cobxkrlb.Text;
            _context.SaveChanges();
            MessageBox.Show("入住成功，窗口将关闭");
            
            #region 日志纪录
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.客人入住;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "预定入住" + "房租=" + txtfz.Value.ToString();
            logInfo.Save();
            #endregion

            this.Close();
        }
        #endregion

        #region 客人信息维护

        /// <summary>
        /// 增加客人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnkrzj_Click(object sender, EventArgs e)
        {
            //e != null保证第一次直接调用时不执行
            if (IsNewRZRY && e != null)
            {
                MessageBox.Show("当前客人休息还没保存，请先保存后再增加！");
                return;
            }
            var page1 = new TabPage("新客人");
            tabkrxx.Controls.Add(page1);
            currentRzryModel = new RZRY();
            Rzrys.Add(currentRzryModel);
            IsNewRZRY = true;
            currentRzryModel.KRZT = "在住";
            currentRzryModel.CJRQ = DateTime.Now;
            currentRzryModel.CJRY = UserLoginInfo.FullName;
            var uckrxx1 = new uckrxx(currentRzryModel);
            uckrxx1.FindCallBack = uckrxxFindCallBack;
            page1.Controls.Add(uckrxx1);
            tabkrxx.SelectedTab = page1;
            btnkrsc.Enabled = Rzrys.Count > 1;
            txtkrld.Enabled = Rzrys.Count > 1;
            btndy.Enabled = false;
        }

        private UV_ALLKR uckrxxFindCallBack(string krxm)
        {
            var frm = new rzryFind(krxm);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                 if (frm.SelectedRZRY.BMC == "HYK")
            {
                var hyk = _context.HYK.FirstOrDefault(p => p.KH == frm.SelectedRZRY.ID);
                if (hyk != null)
                {
                    MessageBox.Show("客人:" + hyk.XM + "是" + hyk.HYKLX.HYK_LX + "会员" + ",不忘了打折:" + hyk.HYKLX.ZK + "折");
                }
            }
                return frm.SelectedRZRY;
            }
            else
                return null;
        }
        /// <summary>
        /// 入住人员删除或离店后的操作
        /// </summary>
        private void RZRYDeleteAfter()
        {
            Rzrys.Remove(currentRzryModel);
            tabkrxx.Controls.Remove(tabkrxx.SelectedTab);
            btnkrsc.Enabled = Rzrys.Count > 1;
            txtkrld.Enabled = Rzrys.Count > 1;
            IsNewRZRY = false;
            currentRzryModel = Rzrys.First();
            tabkrxx.SelectedIndex = 0;
        }

        /// <summary>
        /// 删除客人信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnkrsc_Click(object sender, EventArgs e)
        {
            if (Rzrys.Count == 1)
                return;
            if (_context.RZRY.Count(p => p.ID == currentRzryModel.ID) > 0)
            {
                _context.RZRY.Remove(currentRzryModel);
                _context.SaveChanges();
            }
            RZRYDeleteAfter();
             
            #region 日志纪录
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.删除客人;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "客人姓名:" + currentRzryModel.KRXM;
            logInfo.Save();
            #endregion
        }

        private void txtkrld_Click(object sender, EventArgs e)
        {
            if (Rzrys.Count == 1)
                return;
            currentRzryModel.KRZT = "离店";
            _context.SaveChanges();
            RZRYDeleteAfter();
        }
        //保存客人信息
        private void btnksbc_Click(object sender, EventArgs e)
        {
            (tabkrxx.SelectedTab.Controls[0] as uckrxx).UpdateRZRY();
            if (!CheckDataRZRY())
                return;
            if (IsNewRZRY)
            {
                _context.RZRY.Add(currentRzryModel);
                currentRzryModel.RZJL = rzjlModel;
            }
            else
            {
                currentRzryModel.XGRQ = DateTime.Now;
                currentRzryModel.XGRY = UserLoginInfo.FullName;
            }
            IsNewRZRY = false;
            _context.SaveChanges();
            tabkrxx.SelectedTab.Text = currentRzryModel.KRXM;
            btndy.Enabled = true;
            if (currentRzryModel.KRXM != "新客人")
                MessageBox.Show("客人信息保存成功");
        }

        private bool CheckDataRZRY()
        {
            return true;
        }

        #endregion


        private void cobxxydw_DropDown(object sender, EventArgs e)
        {
            var frm = new xydwFind();
            if (frm.ShowDialog() != DialogResult.OK)
                return;
            cobxxydw.Items.Clear();
            cobxxydw.Items.Add(new NameValue() { Name = frm.SelectedXYDW.DWMC, Value = frm.SelectedXYDW.XYDM });
            cobxxydw.SelectedIndex = 0;

            var xyfj = _context.XYFJ.FirstOrDefault(p => p.XYDW.ID == frm.SelectedXYDW.ID && p.ROOM_TYPE.ID == roomModel.ROOM_TYPE.ID);
            if (xyfj != null)
            {
                txtzk.Value = Math.Round(xyfj.FJ / Convert.ToDecimal(lbysj.Text), 2);
                txtfz.Value = xyfj.FJ;
            }

        }

        private void jddjFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (IsNewRZRY && IsEdit)
                btnksbc_Click(btnksbc, null);
        }

        private void txtts_Leave(object sender, EventArgs e)
        {
            var xtcs = XTCSModel.GetXTCS;
            dtpldrq.Value = Convert.ToDateTime(dtpddrq.Value.Date.AddDays((double)txtts.Value).ToString("yyyy-MM-dd ") + xtcs.JBTFZ_SJ);
        }

        private void dtpldrq_ValueChanged(object sender, EventArgs e)
        {
            var val = (dtpldrq.Value.Date - dtpddrq.Value.Date).Days;
            txtts.Value = val >= 1 ? val : 0;//钟点房可以是0
            //txtyj.Value = txtts.Value * roomModel.ROOM_TYPE.YJ * yxRoom.Count;
        }

        private void txtFind_TextChanged(object sender, EventArgs e)
        {
            grid1.AutoGenerateColumns = false;
            if (txtFind.Text.Length > 0)
                grid1.DataSource = kxRoom.Where(p => p.ID.Substring(0, txtFind.Text.Length) == txtFind.Text).ToList();
            else
                grid1.DataSource = kxRoom;
            btnyc.Enabled = grid2.Rows.Count > 1;
            btnzj.Enabled = grid1.Rows.Count > 0;
        }
        //打印登记单
        private void btndy_Click(object sender, EventArgs e)
        {
            if (currentRzryModel == null)
                return;
            //日志纪录,真实打印时纪录，预览时不纪录日志
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.打印;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "打印人员登记表";

            var qry = _context.UV_RZJL_RZRY.AsNoTracking().Where(p => p.RZRY_ID == currentRzryModel.ID);
            hotel.Win.Report.ReportEntry.ShowRuZhuDengJiBill(XTCSModel.GetXTCS.JDMC, qry,logInfo);
        }

        private void tabkrxx_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabkrxx.SelectedTab == null)
                return;
            var uc = tabkrxx.SelectedTab.Controls[0] as uckrxx;
            currentRzryModel = uc.Rzry;
        }

        private void lbzh_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(lbzh.Text);
            MessageBox.Show("入住账号已复制到剪切板");
        }
        //打印押金,增加时
        private void btnprintJy_Click(object sender, EventArgs e)
        {
            #region 日志
            CcrzInfo logInfo = null;
            logInfo = new CcrzInfo();
            logInfo.Abstract = LogAbstractEnum.打印;
            logInfo.RoomId = rzjlModel.ROOM_ID;
            logInfo.Rzid = rzjlModel.ID;
            logInfo.Message = "打印押金单,金额:" + rzjlModel.YJ.ToString();
            #endregion
            var xfjlModel = _context.XFJL.Where(p => p.RZJL_ID == rzjlModel.ID && p.XFXM_MC == "押金").FirstOrDefault();
            if (xfjlModel == null)
            {
                MessageBox.Show("没有找到押金数据");
                return;
            }
            hotel.Win.Report.ReportEntry.ShowYaJinBill(xfjlModel.ID, logInfo);
        }
        //协议房价
        private void cobxsyjg_SelectedIndexChanged(object sender, EventArgs e)
        {
            var d = cobxsyjg.SelectedItem as RoomTypePrice;
            if (d == null)
                return;
            txtfz.Value = d.XYJG;
            txtzk.Value = Math.Round(txtfz.Value / Convert.ToDecimal(lbysj.Text),2);
            //txtts.Enabled = RoomStstusCnName.ZhongDian != d.XYMC;
            //钟点房,ZDF_SC钟点房时长
            if (RoomStstusCnName.ZhongDian == d.XYMC)
                dtpldrq.Value = dtpddrq.Value.AddHours((double)d.ZDF_SC);
        }

        private void cobxkrlb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cobxsyjg.DataSource == null)
                return;
            foreach (var item in cobxsyjg.DataSource as List<RoomTypePrice> )
            {
                if (item.XYMC == cobxkrlb.Text)
                {
                    cobxsyjg.SelectedItem = item;
                    break;
                }
            }
        }

        private void jddjFrm_Shown(object sender, EventArgs e)
        {
            if (roomModel.ZT == RoomStstusCnName.SuoDing)
            {
                MessageBox.Show("锁定房不能预定或入住，请先解锁");
                this.Close();
            }
        }
    }
}
